#include "logger.hpp"
#include <cstdio>
#include <cstdarg>
#include <iostream>
#include <sstream>
#include <sys/time.h>

void Logger::setLogFile(const char *file_name)
{
	_log_file.open(file_name,std::ios_base::trunc);
	if(!_log_file.is_open()) {
		std::stringstream s;
		s << "Warning: error while open opening ";
		s << file_name;
		s << " for writting.";
		this->error(s.str().c_str());
	}
}

void Logger::log(const char *str,...)
{
	char *buf = new char[1024];
	va_list ap;

	va_start(ap, str);
	vsprintf(buf, str,ap);
	va_end(ap);

	/* Get the current system time */
	timeval tv;
	gettimeofday(&tv, NULL);

	/* Print the log entry */
	std::stringstream time_str;
	time_str << "["
	         << ((((tv.tv_sec / 60) / 60) % 24 < 10) ? "0" : "")
	         << (int)(((tv.tv_sec / 60) / 60) % 24)
	         << ":"
	         << (((tv.tv_sec / 60) % 60 < 10) ? "0" : "")
	         << (int)((tv.tv_sec / 60) % 60)
	         << ":"
	         << ((tv.tv_sec % 60 < 10) ? "0" : "")
	         << (int)(tv.tv_sec % 60)
	         << "."
	         << (((tv.tv_usec / 10000) % 100) < 10 ? "0" : "")
	         << (int)((tv.tv_usec / 10000) % 100)
	         << "] ";

	if(_log_file.is_open()) {
		_log_file << time_str.str() << buf << "\n";
	}

	delete[] buf;
}

void Logger::error(const char *error_text)
{
	std::cerr << "Error: " << error_text << std::endl;
}
